package com.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.db.domain.*;
import com.mall.db.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 页面跳转控制器
 */
@Controller
@RequestMapping(("/page"))
public class PageController {

    @Value("${email.times}")
    private long emailTimes;

    @Resource(name="memberService")
    private MemberService ms;
    @Resource(name="membersService")
    private MembersService msc;
    @Resource(name="addressService")
    private AddressService as;
    @Resource(name="feedbackService")
    private FeedbackService fcs;
    @Resource(name="schedulerService")
    private SchedulerService ss;
    @Resource(name = "orderService")
    private OrderService ps;
    @Autowired
    private CategoryService cs;
    @Autowired
    private BrandService bs;
    @Autowired
    private CouponsService cp;


    @Autowired
    private GoodsService gs;

    @RequestMapping("/index")
    public String index(){
        return "/views/index";
    }
    @RequestMapping("/main")
    public String main(){
        return "/views/main";
    }
    @RequestMapping("/login")
    public String login(){
        return "/views/login";
    }
    @RequestMapping("/members")
    public String members(){
        return "/views/members/members";
    }
    @RequestMapping("/footprint")
    public String footprint(){
        return "/views/footprint/footprint";
    }
    @RequestMapping("/address")
    public String address(){
        return "/views/address/address";
    }
    @RequestMapping("/feedback")
    public String feedback(){
        return "/views/feedback/feedback";
    }

    @RequestMapping("/forgetPwd")
    public String forgetPwd(){
        return "/views/forgetPwd";
    }

    @RequestMapping("/forgetNext")
    public String forgetNext(@RequestParam(name="email") String email,
                             ModelMap mmap){
        mmap.addAttribute("email",email);
        return "/views/forgetNext";
    }


    @RequestMapping("/forgetVerify")
    public String forgetVerify(@RequestParam(name="code") String code,
                               @RequestParam(name="token") String token,
                               ModelMap mmap,HttpServletResponse res,HttpSession session){
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            code = new String(decoder.decodeBuffer(code), "utf-8");
            token = new String(decoder.decodeBuffer(token), "utf-8");
            //判断时间的有效性
            if(System.currentTimeMillis() - Long.parseLong(code) > emailTimes){
                mmap.addAttribute("tips","邮件链接已过期，请重新获取!");
                return "/views/tips";
            }
            if(!StringUtils.isEmpty(token)){
                QueryWrapper<Member> qw = new QueryWrapper<>();
                qw.eq("email",token);
                Member m = ms.getOne(qw);
                if(m!=null){
                    mmap.addAttribute("id",m.getId());
                    mmap.addAttribute("email",token);
                    code = (new Random().nextInt(999)+1000) + "";
                    session.setAttribute("mobileCode",code);
                    mmap.addAttribute("code",code);
                    return "/views/pwdEdit";
                }else{
                    mmap.addAttribute("tips","该邮箱未注册到系统!");
                    return "/views/tips";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        mmap.addAttribute("tips","密码找回失败!");
        return "/views/tips";
    }

    @RequestMapping("/{root}/{pageName}")
    public String createPageLink(@PathVariable(name = "root") String root,
                                 @PathVariable(name = "pageName") String page){
        return String.format("/views/%s/%s",root,page);
    }

    @RequestMapping("/system/memberEdit/{id}")
    public String pageUpdate(@PathVariable(name = "id") int id, ModelMap mmap){
        mmap.addAttribute("m",ms.getById(id));
        return String.format("/views/system/memberEdit");
    }
    @RequestMapping("/members/membersEdit/{id}")
    public String membersUpdate(@PathVariable(name = "id") int id, ModelMap mmap){
        mmap.addAttribute("mst",msc.getById(id));
        return String.format("/views/members/membersEdit");
    }
    @RequestMapping("/address/addressEdit/{id}")
    public String addressUpdate(@PathVariable(name = "id") int id, ModelMap mmap){
        mmap.addAttribute("ae",as.getById(id));
        return String.format("/views/address/addressEdit");
    }
    @RequestMapping("/feedback/feedbackEdit/{id}")
    public String feedbackUpdate(@PathVariable(name = "id") int id, ModelMap mmap){
        mmap.addAttribute("fd",fcs.getById(id));
        return String.format("/views/feedback/feedbackEdit");
    }

    @RequestMapping("/order/details/{id}")
    public String details(@PathVariable(name = "id") int id, ModelMap mmap){
        mmap.addAttribute("m",ps.getById(id));
        return String.format("/views/order/details");
    }

    @RequestMapping("/order/send/{id}")
    public String send(@PathVariable(name = "id") int id, ModelMap mmap){
        mmap.addAttribute("m",ps.getById(id));
        return String.format("/views/order/sendAdd");
    }
    @RequestMapping("/order/paid/{id}")
    public String paid(@PathVariable(name = "id") int id, ModelMap mmap){
        mmap.addAttribute("m",ps.getById(id));
        return String.format("/views/order/paidAdd");
    }
    @RequestMapping("/order/refund/{id}")
    public String refund(@PathVariable(name = "id") int id, ModelMap mmap){
        mmap.addAttribute("m",ps.getById(id));
        return String.format("/views/order/refundAdd");
    }

    @RequestMapping("/system/editQuartz/{jobName}")
    public String editQuartz(@PathVariable(value = "jobName") String jobName,ModelMap mmap){
        mmap.addAttribute("s",ss.getByJobName(jobName));
        return "/views/system/editQuartz";
    }
    @RequestMapping("/system/map/{lng}/{lat}")
    public String map(@PathVariable(value = "lng") Double lng,
                      @PathVariable(value = "lat") Double lat,
                      @RequestParam(value="address") String address,
                      ModelMap mmap){
        if(lng==0.0&&lat==0.0&& !StringUtils.isEmpty(address)){
            mmap.addAttribute("address",address);
        }else{
            mmap.addAttribute("address","");
        }
        //TODO 获取该用户登录时，所在城市信息 经纬度
        lng = lng == 0.0?108.281113:lng;
        lat = lat == 0.0?22.868199:lat;

        mmap.addAttribute("lng",lng);
        mmap.addAttribute("lat",lat);
        return "/views/system/map";
    }

    @RequestMapping("/getImageCode")
    public void getImageCode(HttpSession session, HttpServletResponse response){
        int width = 100;
        int height = 50;
        try {
            BufferedImage buffer = new BufferedImage(width, height, 1);
            //BufferedImage buffer = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
            //创建一个2d 画板
            Graphics2D g = buffer.createGraphics();

            //设置颜色
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);


            StringBuffer sb = new StringBuffer();
            int x = 0, y = 0;
            Random d = new Random();
            for (int i = 0; i < 6; i++) {
                String num = String.valueOf(d.nextInt(10));
                Font f = new Font("Times New Roman", Font.BOLD, d.nextInt(15) + 25);
                g.setFont(f);
                int a = d.nextInt(2);
                if ((a == 0 && x < 2) || y > 3) {
                    x++;
                    g.setColor(Color.black);
                } else {
                    y++;
                    g.setColor(Color.red);
                    sb.append(num);
                }
                g.drawString(num, 13 * i + 13, 35);
            }
            //存入到会话
            session.setAttribute("imgCode", sb.toString());


            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");

            ServletOutputStream sos = response.getOutputStream();
            ImageIO.write(buffer, "jpeg", sos);

            sos.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping("/look")
    public String look(Goods goods,ModelMap mmap){
        Goods goods1 = gs.getById(goods.getId());

        Category   c =cs.getById(goods1.getCategories());
        if (c==null){
            c= new Category();
            c.setTitle("类目不存在");
        }
        mmap.addAttribute("c",c);
        Brand b = bs.getById(goods1.getBrandOwner());
        if (b==null){
            b=new Brand();
            b.setTitle("品牌不存在");
        }
        mmap.addAttribute("b",b);
        mmap.addAttribute("goods",goods1);
        return "/views/lsl/goodsLook";
    }
    @RequestMapping("/coupons/couponsEdit")
    public String couponsEdit(Coupons coupons, ModelMap mmap){
        coupons = cp.getById(coupons.getId());
        if (coupons!=null){
            mmap.addAttribute("coupons",coupons);
        }
        return "/views/coupons/couponsEdit";
    }





}
